<template>
  <div class="balance">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="balance-card">
          <template #header>
            <div class="card-header">
              <span>我的卡密</span>
              <el-button type="primary" @click="$router.push('/home/recharge')">
                立即购买
              </el-button>
            </div>
          </template>
          <div class="balance-info">
            <div class="balance-amount">
              <span class="amount">{{ balance.amount }}</span>
              <span class="unit">条</span>
            </div>
            <el-progress
              :percentage="balance.usagePercentage"
              :status="balance.usagePercentage < 20 ? 'exception' : ''"
            />
            <div class="balance-tips" v-if="balance.usagePercentage < 20">
              <el-alert
                title="余额不足提醒"
                type="warning"
                :closable="false"
                show-icon
              >
                <p>当前剩余额度较低，建议及时充值以免影响使用</p>
              </el-alert>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="16">
        <el-card class="usage-card">
          <template #header>
            <div class="card-header">
              <span>使用记录</span>
              <el-radio-group v-model="timeRange" size="small">
                <el-radio-button label="week">最近7天</el-radio-button>
                <el-radio-button label="month">最近30天</el-radio-button>
                <el-radio-button label="year">最近12个月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="usage-chart" ref="chartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>消费明细</span>
          <div class="header-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
            />
            <el-button type="primary" size="small" @click="exportDetails">
              导出明细
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="usageDetails" style="width: 100%" v-loading="loading">
        <el-table-column prop="time" label="使用时间" width="180" />
        <el-table-column prop="appName" label="应用名称" />
        <el-table-column prop="type" label="使用类型">
          <template #default="{ row }">
            <el-tag :type="getUsageTypeTag(row.type)">{{ row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="使用额度" width="120">
          <template #default="{ row }">
            <span class="usage-amount">-{{ row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="balance" label="剩余额度" width="120" />
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

const router = useRouter()
const loading = ref(false)
const chartRef = ref(null)
const timeRange = ref('week')
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 模拟数据
const balance = ref({
  amount: 8526,
  usagePercentage: 15
})

const usageDetails = ref([
  {
    time: '2025-02-22 13:45:22',
    appName: 'AI文章助手',
    type: '文章生成',
    amount: 5,
    balance: 8526
  },
  {
    time: '2025-02-22 13:40:15',
    appName: '数据分析工具',
    type: '数据处理',
    amount: 10,
    balance: 8531
  }
])

// 获取使用类型标签样式
const getUsageTypeTag = (type) => {
  const types = {
    '文章生成': '',
    '数据处理': 'success',
    '图片生成': 'warning',
    '代码生成': 'info'
  }
  return types[type] || ''
}

// 初始化图表
let chart = null
const initChart = () => {
  if (!chartRef.value) return
  
  chart = echarts.init(chartRef.value)
  updateChart()
}

// 更新图表数据
const updateChart = () => {
  if (!chart) return

  // 模拟数据
  const dates = []
  const usage = []
  const today = new Date()
  
  for (let i = 6; i >= 0; i--) {
    const date = new Date(today)
    date.setDate(date.getDate() - i)
    dates.push(date.toLocaleDateString())
    usage.push(Math.floor(Math.random() * 100))
  }

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value',
      name: '使用额度'
    },
    series: [
      {
        name: '使用额度',
        type: 'line',
        smooth: true,
        data: usage,
        areaStyle: {
          opacity: 0.1
        }
      }
    ]
  }

  chart.setOption(option)
}

// 导出明细
const exportDetails = () => {
  ElMessage.success('明细导出成功')
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  // 重新加载数据
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 重新加载数据
}

// 监听时间范围变化
watch(timeRange, () => {
  updateChart()
})

// 监听窗口大小变化
window.addEventListener('resize', () => {
  chart?.resize()
})

onMounted(() => {
  initChart()
})
</script>

<style scoped>
.balance {
  padding: 20px;
}

.balance-card,
.usage-card,
.detail-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.balance-info {
  text-align: center;
}

.balance-amount {
  margin: 20px 0;
}

.amount {
  font-size: 36px;
  font-weight: bold;
  color: #409EFF;
}

.unit {
  font-size: 16px;
  margin-left: 5px;
}

.balance-tips {
  margin-top: 20px;
}

.usage-chart {
  height: 300px;
}

.usage-amount {
  color: #F56C6C;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
